<template>
  <!--标题栏组件-->
  <div>
    <nav-bar>
      <template v-slot:title
        >购物车(<span>{{ $store.state.cartCount }}</span
        >)</template
      >
    </nav-bar>
    <div class="cart-box">
      <div class="cart-body">
        <van-checkbox-group @change="groupChange  " v-model="result">
          <van-swipe-cell
            :right-width="50"
            v-for="(item, index) in list"
            :key="index"
          >
            <div class="good-item">
              <van-checkbox :name="item.id" />
              <div class="good-img">
                <img :src="item.goods.cover_url" alt="" />
              </div>
              <div class="good-desc">
                <div class="good-title">
                  <span>{{ item.goods.title }}</span>
                  <span style="font-size: 14px; color: #000000"
                    >x{{ item.goods.stock }}</span
                  >
                </div>
                <div class="good-btn">
                  <div class="price">
                    <small>￥</small>{{ item.goods.price + ".00" }}
                  </div>
                  <van-stepper
                    integer
                    :min="1"
                    :max="item.goods.stock"
                    :model-value="item.num"
                    :name="item.id"
                    @change="onChange"
                    async-change
                  />
                </div>
              </div>
            </div>
            <template #right>
              <van-button
                @click="deleteGood(item.id)"
                square
                icon="delete"
                type="danger"
                class="delete-button"
              />
            </template>
          </van-swipe-cell>
        </van-checkbox-group>
      </div>
      <van-submit-bar
        @onclick="ToOrder"
        :price="total * 100"
        button-text="提交订单"
        @submit="onSubmit"

      >
        <van-checkbox v-model:checked="checkAll" @click="allCheck"
          >全选</van-checkbox
        >
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import NavBar from "components/common/NavBar.vue";
import { reactive, toRefs, onMounted, computed } from "vue";
import {
  getCar,
  modifyCart,
  checkedCard,
  deleteCarItem,
} from "network/cart.js";
import { Toast } from "vant";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

export default {
  name: "ShopcartView",
  components: { NavBar },
  setup() {
    const router = useRouter();
    const store = useStore();
    const onSubmit = () => {
      if (state.result.length == 0) {
        Toast.fail("请选择商品进行结算");
      } else {
        router.push({ path: "/createorder" });
      }
    };
    //数据模型
    const state = reactive({
      list: [],
      result: [], //id数组
      checkAll: true,
    });
    //获取购物车信息
    const init = () => {
      getCar("include=goods").then((res) => {
        Toast.loading({ message: "加载中....", forbidClick: true });
        state.list = res.data;
        state.result = res.data
          .filter((n) => n.is_checked == 1)
          .map((item) => item.id);
        return res;
      });
    };
    //异步改变购物车数量
    const onChange = (value, detail) => {
      Toast.loading({ message: "修改中....", forbidClick: true });
      modifyCart(detail.name, { num: value }).then((res) => {
        //在onMounted中的list也要改变
        state.list.forEach((item) => {
          if (item.id == detail.name) {
            item.num = value;
          }
        });
        Toast.clear();
        return res;
      });
    };
    onMounted(() => {
      init();
    });
    //复选框改变处理
    const groupChange = (result) => {
      if (state.result.length == state.list.length) {
        state.checkAll = true;
      } else {
        state.checkAll = false;
      }
      console.log(result);
      state.result = result;
      //更改数据表中选中的状态
      checkedCard({ cart_ids: result });
    };
    //全选功能
    const allCheck = () => {
      if (!state.checkAll) {
        state.result = state.list.map((item) => item.id);
        state.checkAll = true;
      } else {
        state.result = [];
        state.checkAll = false;
      }
    };
    //删除购物车
    const deleteGood = (id) => {
      deleteCarItem(id).then((res) => {
        init(); //重新初始化
        store.dispatch("updateCart"); //改变Vuex中状态的数量
        return res;
      });
    };
    //计算总价
    const total = computed(() => {
      let sum = 0;
      state.list
        .filter((item) => state.result.includes(item.id))
        .forEach((item) => {
          sum += parseInt(item.num) * parseFloat(item.goods.price);
        });
      return sum;
    });
    //跳转到订单预览
    const ToOrder = ()=>{
      router.push({
        path:'/createOrder',
      })
    }

    return {
      ToOrder,
      onSubmit,
      ...toRefs(state),
      onChange,
      groupChange,
      allCheck,
      deleteGood,
      total,
    };
  },
};
</script>

<style scoped>
.cart-body {
  margin: 60px 0 100px 0;
  padding-left: 10px;
}
.good-item {
  display: flex;
  margin-top: 10px;
}
.good-img > img {
  margin-left: 10px;
  margin-right: 10px;
  width: 100px;
  height: auto;
}
.good-item > .good-desc {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
  padding: 20px;
}
.good-item > .good-desc > .good-title {
  font-size: 15px !important;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
.good-item > .good-desc > .good-btn {
  display: flex;
  justify-content: space-between;
}
.good-item > .good-desc > .good-btn > .price {
  font-size: 16px !important;
  color: red;
  line-height: 28px;
}
.good-item > .good-desc > .good-btn > .van-icon-delete {
  font-size: 20px;
  margin-top: 4px;
}
.delete-button {
  width: 50px;
  height: 100%;
}
.empty {
  width: 100%;
  margin: 0 auto;
  text-align: left;
  margin-top: 200px;
}
.cart-box {
  padding: 5px;
}
.van-submit-bar {
  bottom: 50px;
  z-index: 0 !important;
}
</style>